package com.zhangtai.modules.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.config.AsyncEmployeeMethod;
import com.zhangtai.eSign.HttpRest.HttpRest;
import com.zhangtai.eSign.entity.CallbackVo;
import com.zhangtai.eSign.entity.OutSideAccountEntity;
import com.zhangtai.eSign.pdf.ContractPdf;
import com.zhangtai.modules.constVo.ContractConst;
import com.zhangtai.modules.constVo.TodoConst;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.*;
import com.zhangtai.modules.entity.certificate.CertificateEntity;
import com.zhangtai.modules.entity.common.ContractUrlEntity;
import com.zhangtai.modules.entity.common.NoticeEntity;
import com.zhangtai.modules.entity.contract.ContractMangerEntity;
import com.zhangtai.modules.entity.contract.ContractModelEntity;
import com.zhangtai.modules.entity.contract.ProtocolEntity;
import com.zhangtai.modules.entity.contract.ProtocolPersonnelEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.employee.EmployerCompanyEntity;
import com.zhangtai.modules.entity.employee.RelativeRecordsEntity;
import com.zhangtai.modules.entity.system.ContractSubGroupEntity;
import com.zhangtai.modules.service.certificate.CertificateService;
import com.zhangtai.modules.service.common.ContractUrlService;
import com.zhangtai.modules.service.contract.ContractMangerService;
import com.zhangtai.modules.service.contract.ProtocolPersonnelService;
import com.zhangtai.modules.service.contract.ProtocolService;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.employee.EmployerCompanyService;
import com.zhangtai.modules.vo.*;
import com.zhangtai.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.InputStream;
import java.util.*;

/**
 * @Author: ming
 * @Date: 2020/5/28 0028 下午 7:56
 */
@RestController
@RequestMapping("eSign")
@Slf4j
@Api(tags = "e签宝接口")
public class EsignController {
    @Value("${eSign.createContractPath}")
    private String path;
    private static final String redirectUrl = "tcf.zhangtai.com.cn";


    @Value("${eSign.callBackUrl}")
    private String callBackUrl;

    @Value("${eSign.callProtocolBackUrl}")
    private String callProtocolBackUrl;
    @Value("${eSign.certificateCallBackUrl}")
    private String certificateCallBackUrl;


    private static final String initiatorAccountId = "d65ef9e2-a607-11ea-b899-00163e0eb2c4";  //E签宝发起人ID 发起人和监印员最好是同一个人
    //    private static final String sealAdministratorAccountId="1d9d925c-9eed-11ea-bc3c-fefcfeacb9ad"; //E签宝后台系统中监印员的账号id
    private static final String initiatorName = "泰财富监印员"; //E签宝后台系统中监印员的名字
    private static final String authorizationOrganizeId = "f2b92749-10ef-49e6-945c-a9539a5c9a7a";//E签宝内部企业id
    private static final String sealId = "3cc61381-a543-11ea-b899-00163e0eb2c4";//合同印章id


    @Autowired
    private HttpRest httpRest;


    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private EmployeeInfoDao employeeInfoDao;

    @Autowired
    private ContractUrlService contractUrlService;


    @Autowired
    private NoticeDao noticeDao;
    @Autowired
    private EmployerCompanyService employerCompanyService;
    @Autowired
    private ContractModelDao contractModelDao;
    @Autowired
    private EmployerCompanyDao employerCompanyDao;
    @Autowired
    private RelativeRecordsDao relativeRecordsDao;

    @Autowired
    private AsyncEmployeeMethod asyncEmployeeMethod;
    @Autowired
    private LoginController loginController;
    @Autowired
    private ProtocolService protocolService;

    @Autowired
    private ProtocolPersonnelDao protocolPersonnelDao;
    @Autowired
    private ProtocolPersonnelService protocolPersonnelService;
    @Autowired
    private EmployeeInfoService employeeInfoService;
    @Autowired
    private OssUploadService ossUploadService;
    @Autowired
    private ContractMangerService contractMangerService;
    @Autowired
    private ContractController contractController;
    @Autowired
    private ContractMangerDao contractMangerDao;

    @Autowired
    private ContractPdf contractPdf;
    @Autowired
    private CertificateService certificateService;


    @GetMapping("/getUrlByIdCard/{id}")
    @ApiOperation(value = "根据身份证查看劳动合同")
    @PreAuthorize("hasAuthority('emp:htlb:get')")
    public R<List<ContractUrlEntity>> findByIdcard(@PathVariable("id") String id) {
        List<ContractUrlEntity> urlEntities = contractUrlService.getByIdCard(id);
        return R.ok(urlEntities);

    }


    @PostMapping("/getContractUrlPage")
    @ApiOperation(value = "分页查询用户合同信息")
    @PreAuthorize("hasAuthority('emp:htlb:get')")
    public R getContractUrlPage(@RequestBody ContratVo contratVo, HttpServletRequest request) throws Exception {
        R checkR = loginController.checkOrgPermission(request, null, false);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        if (!StringUtils.isEmpty(contratVo.getName())) {
            contratVo.setBlurName(null);
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        String expiredStartTime = "";
        String expiredEndTime = "";
        Date dateNew = new Date();
        if (contratVo.getIsUpcoming()) {
            expiredStartTime = DateUtils.format(dateNew);
            expiredEndTime = DateUtils.format(DateUtils.addDateDays(dateNew, contratVo.getDay()));
        }

        PageResult pageResult = contractUrlService.queryPage(
                contratVo.getName(),
                contratVo.getBlurName(),
                contratVo.getIdCard(),
                contratVo.getContractName(),
                contratVo.getSignedTimeStart(),
                contratVo.getSignedTimeEnd(),
                contratVo.getType(),
                contratVo.getStatus(),
                expiredStartTime,
                expiredEndTime,
                orgIds,
                contratVo.getPageNum(),
                contratVo.getPageSize());

        return R.ok(pageResult);

    }


    @PostMapping("/updateContractUrlStatus")
    @ApiOperation(value = "合同终止 修改状态")
    @SysAuthorityLog(value = "合同终止 修改状态")
    @PreAuthorize("hasAuthority('emp:contract:update')")
    public R updateContractUrlStatus(@RequestParam("id") String id, @RequestParam(value = "status", defaultValue = "4") Integer status) {
        ContractUrlEntity contractUrlEntity = new ContractUrlEntity();
        contractUrlEntity.setId(new Long(id));
        contractUrlEntity.setStatus(status);

        return contractUrlService.updateByIdE(contractUrlEntity);

    }


    @PostMapping("/getCompanyList")
    @ApiOperation(value = "甲方主体列表")
    public R<List<EmployerCompanyEntity>> getCompanyList(EmployerCompanyVo vo) {
        List<EmployerCompanyEntity> companyEntityList = employerCompanyDao.selectList(new QueryWrapper<EmployerCompanyEntity>().like(!StringUtils.isEmpty(vo.getName()), "name", vo.getName()).
                like(!StringUtils.isEmpty(vo.getRepresentative()), "representative", vo.getRepresentative()).orderByAsc("id"));

        return R.ok(companyEntityList);
    }

    @PostMapping("/getCompanyListAuth")
    @ApiOperation(value = "带权限甲方主体列表")
    public R<List<EmployerCompanyEntity>> getCompanyListAuth(EmployerCompanyVo vo, HttpServletRequest request) throws Exception {
        //根据登录人id查询
        R checkR = loginController.checkContractPermission(request);
        if (!R.isOk.equals(checkR.getStatus())) {
            return checkR;
        }
        List<ContractSubGroupEntity> contractSubs = (List<ContractSubGroupEntity>) checkR.getData();
        ArrayList<Long> contractIds = new ArrayList<Long>();
        for (ContractSubGroupEntity item : contractSubs
        ) {
            contractIds.add(item.getId());
        }
        List<EmployerCompanyEntity> companyEntityList = employerCompanyDao.selectList(new QueryWrapper<EmployerCompanyEntity>().like(!StringUtils.isEmpty(vo.getName()), "name", vo.getName()).
                like(!StringUtils.isEmpty(vo.getRepresentative()), "representative", vo.getRepresentative()).in("id", contractIds).
                orderByAsc("id"));

        return R.ok(companyEntityList);
    }

    @PostMapping("/getContractModelList")
    @ApiOperation("合同模板")
    public R<List<ContractModelEntity>> getContractModelList(String type, String kind) {
        List<ContractModelEntity> contractModelEntityList = contractModelDao.selectList(new QueryWrapper<ContractModelEntity>().eq("is_delete", 0).eq("kind", kind).eq("type", type));
        return R.ok(contractModelEntityList);
    }

    @PostMapping("/sendContract")
    @ApiOperation(value = "签合同 并返回合同地址 ")
    @SysAuthorityLog(value = "签合同 并返回合同地址")
//    @PreAuthorize("hasAuthority('emp:contract:send')")
//    @Transactional
    public R createOutsideAccountById(@RequestBody @Valid ExportContractPdfVo vo, HttpServletRequest request) throws Exception {
        Long oid = Long.parseLong(vo.getOid());
        JSONObject userInfo = loginController.getUserInfo(request).getData();
        ContractMangerEntity mangerEntity = contractMangerService.getByIdE(vo.getId());
        if (ObjectUtils.isEmpty(mangerEntity)) {
            return R.error("合同信息不存在！");
        }
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectById(oid);
        String idcard = employeeInfoEntity.getIdcard();
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return R.error("根据id查询员工为空");
        }
        String realName = employeeInfoEntity.getName();
        if (StringUtils.isEmpty(realName)) {
            return R.error("新员工姓名不能为空");
        }
        if (StringUtils.isEmpty(idcard)) {
            return R.error("新员工身份证不能为空");
        }
        String mobile = employeeInfoEntity.getMobile();
        if (StringUtils.isEmpty(mobile)) {
            return R.error("新员工手机号不能为空");
        }

        //封装e签宝 创建外部用户所需要的参数
        OutSideAccountEntity outSideAccountEntity = getOutSideAccountEntity(realName, idcard, mobile, idcard);
        String uniqueId = idcard;
//        先根据唯一id查询外部用户是否已经创建
        R<String> outsideUser = httpRest.queryOutsideUser(uniqueId);
        if (outsideUser.getFlag()) {
            String s = outsideUser.getData();
            log.info("查询用户为：{}", s);
            uniqueId = s;
        } else {
            // 如果查不到用户，则调用e签宝接口创建外部用户
            R<String> outSideAccount = httpRest.createOutSideAccount(outSideAccountEntity);
            if (!outSideAccount.getFlag()) {
                return outSideAccount;
            }
            //返回e签宝的accountId
//            uniqueId= outSideAccount.getData();
        }
        ContractModelEntity modelEntity = contractModelDao.selectOne(new QueryWrapper<ContractModelEntity>().eq("id", vo.getModelId()).eq("is_delete", 0));
        if (ObjectUtils.isEmpty(modelEntity)) {
            return R.error("模板不存在！");
        }
        log.info("用户账号:{}", uniqueId);

        EmployerCompanyEntity companyEntity = employerCompanyService.getByIdE(Long.parseLong(vo.getCompanyId()));
        EmployerCompanyEntity serverCompany = null;
        if (!ObjectUtils.isEmpty(vo.getServerId())) {
            serverCompany = employerCompanyService.getByIdE(Long.parseLong(vo.getServerId()));
        }
        List<RelativeRecordsEntity> relativeRecordsEntityList = relativeRecordsDao.selectList(new QueryWrapper<RelativeRecordsEntity>().eq("oid", vo.getOid()).eq("is_delete", 0));

        //生成合同pdf
        R pdfR = contractPdf.createPdfNew(vo, companyEntity, serverCompany, modelEntity, relativeRecordsEntityList, userInfo);
        if (!pdfR.getFlag()) {
            return pdfR;
        }
        String path = pdfR.getData().toString();
        //上传签约合同
        R<String> r = httpRest.upLoadNewPdf(path);
        if (!r.getFlag()) {
            return r;
        }
        // e签宝返回docKey
        String contractFileKey = r.getData();
        //        开始签合同
        String s = null;
        if (ContractConst.CONTRACT_TYPE_NEW.equals(vo.getType())) {
            s = getNewContractParam(s, modelEntity, companyEntity, mobile, contractFileKey, idcard, serverCompany);
        } else if (ContractConst.CONTRACT_TYPE_RENEW.equals(vo.getType())) {
            s = getReNewContractParam(s, modelEntity, companyEntity, mobile, contractFileKey, idcard, serverCompany);
        } else if (ContractConst.CONTRACT_TYPE_TERMINATE.equals(vo.getType())) {
            s = getTerminate(s, modelEntity, companyEntity, mobile, contractFileKey, idcard, serverCompany);
        } else {
            s = getTransferContractParam(s, modelEntity, companyEntity, mobile, contractFileKey, idcard, serverCompany);
        }
        log.info("请求体是：{}", s);
//        开始盖企业章
        R<Map<String, Object>> sign = httpRest.sign(s);
        if (!sign.getFlag()) {
            return sign;
        }
        //企业盖章后返回流程id,
        String signUrl = (String) sign.getData().get("signUrl");
        Integer flowId = TypeCastUtils.toInt(sign.getData().get("docId"));
        log.info("合同流程id:{}", flowId);
        mangerEntity.setEsignFlowId(flowId);
        if (!ObjectUtils.isEmpty(vo.getRepresentativeStart())) {
            mangerEntity.setContractBeginDate(DateUtils.parseDateYMD(vo.getRepresentativeStart()));
        }
        if (!ObjectUtils.isEmpty(vo.getRepresentativeEnd())) {
            mangerEntity.setContractEndDate(DateUtils.parseDateYMD(vo.getRepresentativeEnd()));
        }
        mangerEntity.setEmployerCompanyId(companyEntity.getId());
        mangerEntity.setEmployerCompany(companyEntity.getName());
        mangerEntity.setIsSendContract(1);
        mangerEntity.setCallbackStatus(0);
        mangerEntity.setContractTimeType(vo.getRepresentativeLimit());
        mangerEntity.setContractType(vo.getContractType());
        contractMangerService.updateByIdE(mangerEntity);
        JSONObject jsonObject = new JSONObject();


        jsonObject.put("signUrl", signUrl);
        if (ContractConst.CONTRACT_MANGER_LAOB.equals(vo.getContractType())) {
            employeeInfoEntity.setEsignFlowId(flowId);
//            employeeInfoEntity.setSignDate(new Date());//更新签约时间
            employeeInfoEntity.setIsSendContract(0); //是否发送合同 0：未发送，1：已发送
            employeeInfoDao.updateById(employeeInfoEntity); //
        }
        //将签合同地址发送邮件给员工
        String mail = employeeInfoEntity.getPrivatemail();
//
        //修改发送信息方式  2020123111：13
        //新签合同并且是劳动合同

        asyncEmployeeMethod.sendEmail(mail, oid, signUrl, "彰泰集团：您有一份合同需要签署");


        return R.ok(jsonObject);
    }


    @PostMapping("/saveProtocolInfo")
    @ApiOperation(value = "生成协议 并返回合同地址 ")
    @SysAuthorityLog(value = "生成协议 并返回合同地址")
    public R saveProtocolInfo(@RequestParam(value = "ProtocolPersonnelId") String ProtocolPersonnelId, HttpServletRequest request) throws Exception {
        ProtocolPersonnelEntity protocolPersonnelEntity = protocolPersonnelService.getByIdE(Long.valueOf(ProtocolPersonnelId));
        ProtocolEntity protocolEntity = protocolService.getByIdE(protocolPersonnelEntity.getProtocolId());
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectById(protocolPersonnelEntity.getOid());
        String idcard = employeeInfoEntity.getIdcard();
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return R.error("根据id查询员工为空");
        }
        String realName = employeeInfoEntity.getName();
        if (StringUtils.isEmpty(realName)) {
            return R.error("新员工姓名不能为空");
        }
        if (StringUtils.isEmpty(idcard)) {
            return R.error("新员工身份证不能为空");
        }
        String mobile = employeeInfoEntity.getMobile();
        if (StringUtils.isEmpty(mobile)) {
            return R.error("新员工手机号不能为空");
        }
        //封装e签宝 创建外部用户所需要的参数
        OutSideAccountEntity outSideAccountEntity = getOutSideAccountEntity(realName, idcard, mobile, idcard);
        String uniqueId = idcard;
//        先根据唯一id查询外部用户是否已经创建
        R<String> outsideUser = httpRest.queryOutsideUser(uniqueId);
        if (outsideUser.getFlag()) {
            String s = outsideUser.getData();
            log.info("查询用户为：{}", s);
            uniqueId = s;
        } else {
            // 如果查不到用户，则调用e签宝接口创建外部用户
            R<String> outSideAccount = httpRest.createOutSideAccount(outSideAccountEntity);
            if (!outSideAccount.getFlag()) {
                return outSideAccount;
            }
            //返回e签宝的accountId
//            uniqueId= outSideAccount.getData();
        }
        ContractModelEntity modelEntity = contractModelDao.selectOne(new QueryWrapper<ContractModelEntity>().eq("id", protocolEntity.getTemplate()).eq("is_delete", 0));
        if (ObjectUtils.isEmpty(modelEntity)) {
            return R.error("模板不存在！");
        }
        log.info("用户账号:{}", uniqueId);

        EmployerCompanyEntity companyEntity = employerCompanyService.getByIdE(protocolEntity.getCompanyId());

        //生成协议pdf
        R pdfR = contractPdf.createProtocolPdf(protocolEntity, protocolPersonnelEntity, companyEntity, modelEntity);
        if (!pdfR.getFlag()) {
            return pdfR;
        }
        String path = pdfR.getData().toString();
        //上传协议
        R<String> r = httpRest.upLoadNewPdf(path);
        if (!r.getFlag()) {
            return r;
        }
        // e签宝返回docKey
        String contractFileKey = r.getData();
        // String contractFileKey ="";
        //        开始签合同
        String s;
//        if (modelEntity.getDetailType().equals("7")) {
//            s = "{\"callbackUrl\":\"" + callProtocolBackUrl + "\",\"initiatorAccountId\":\"" + companyEntity.getInitiatorAccountId() + "\",\"initiatorName\":\"" + companyEntity.getInitiatorName() + "\",\"redirectUrl\":\"\",\"initiatorOrganizeId\":\"" + companyEntity.getESignOrgId() + "\",\"signDocs\":[{\"docFilekey\":\"" + contractFileKey + "\",\"docName\":\"培训协议\"}],\"signers\":[{\"accountId\":\"" + companyEntity.getInitiatorAccountId() + "\",\"accountType\":1,\"autoSign\":true,\"authorizationOrganizeId\":\"" + companyEntity.getAuthorizationOrganizeId() + "\",\"authorizationOrganizeNo\":\"\",\"signDocDetails\":[{\"docFilekey\":\"" + contractFileKey + "\",\"signPos\":[{\"addSignTime\":false,\"edgePosition\":1,\"posPage\":2,\"sealId\":\"" + companyEntity.getSealId() + "\",\"qrcodeSign\":false,\"sealType\":\"1\",\"posX\":100,\"posY\":-25,\"key\":\"甲方\",\"keyIndex\":100,\"signIdentity\":\"ORGANIZE\",\"signType\":4}]}],\"signOrder\":1},{\"uniqueId\":\"" + uniqueId + "\",\"accountType\":2,\"autoSign\":false,\"contactMobile\":\"" + mobile + "\",\"signDocDetails\":[{\"docFilekey\":\"" + contractFileKey + "\",\"signPos\":[{\"addSignTime\":false,\"posPage\":\"2\",\"posX\":50,\"posY\":15,\"key\":\"乙方\",\"keyIndex\":100,\"qrcodeSign\":false,\"sealType\":\"0\",\"signIdentity\":\"PERSON\",\"signType\":4,\"width\":100}]}],\"signOrder\":2}],\"subject\":\"培训协议\"}";
//        } else {
//            s = "{\"callbackUrl\":\"" + callProtocolBackUrl + "\",\"initiatorAccountId\":\"" + companyEntity.getInitiatorAccountId() + "\"" +
//                    ",\"initiatorName\":\"" + companyEntity.getInitiatorName() + "\",\"redirectUrl\":\"\"," +
//                    "\"initiatorOrganizeId\":\"" + companyEntity.getESignOrgId() + "\"," +
//                    "\"signDocs\":[{\"docFilekey\":\"" + contractFileKey + "\",\"docName\":\"培训协议\"}]," +
//                    "\"signers\":[{\"accountId\":\"" + companyEntity.getInitiatorAccountId() + "\",\"accountType\":1,\"autoSign\":true," +
//                    "\"authorizationOrganizeId\":\"" + companyEntity.getAuthorizationOrganizeId() + "\",\"authorizationOrganizeNo\":\"\"," +
//                    "\"signDocDetails\":[{\"docFilekey\":\"" + contractFileKey + "\",\"signPos\":[{\"addSignTime\":false,\"edgePosition\":1," +
//                    "\"posPage\":2,\"sealId\":\"" + companyEntity.getSealId() + "\",\"qrcodeSign\":false,\"sealType\":\"1\"," +
//                    "\"posX\":100,\"posY\":-25,\"key\":\"甲方\",\"keyIndex\":100,\"signIdentity\":\"ORGANIZE\",\"signType\":4}]}],\"signOrder\":1}," +
//                    "{\"uniqueId\":\"" + uniqueId + "\",\"accountType\":2,\"autoSign\":false,\"contactMobile\":\"" + mobile + "\"," +
//                    "\"signDocDetails\":[{\"docFilekey\":\"" + contractFileKey + "\"," +
//                    "\"signPos\":[{\"addSignTime\":false,\"posPage\":\"2\",\"posX\":50,\"posY\":15,\"key\":\"乙方\",\"keyIndex\":100," +
//                    "\"qrcodeSign\":false,\"sealType\":\"0\",\"signIdentity\":\"PERSON\",\"signType\":4,\"width\":100}]}]," +
//                    "\"signOrder\":2}],\"subject\":\"培训协议\"}";
//        }
        JSONObject object = new JSONObject();
        object.put("callbackUrl", callProtocolBackUrl);
        object.put("initiatorAccountId", companyEntity.getInitiatorAccountId());
        object.put("initiatorName", companyEntity.getInitiatorName());
        object.put("redirectUrl", "");
        object.put("initiatorOrganizeId", companyEntity.getESignOrgId());
        JSONArray array1 = new JSONArray();
        JSONObject obj1 = new JSONObject();
        obj1.put("docFilekey", contractFileKey);
        obj1.put("docName", "培训协议");
        array1.add(obj1);
        object.put("signDocs", array1);

        JSONArray array2 = new JSONArray();
        JSONObject obj2 = new JSONObject();
        obj2.put("accountId", companyEntity.getInitiatorAccountId());
        obj2.put("accountType", 1);
        obj2.put("autoSign", true);
        obj2.put("authorizationOrganizeId", companyEntity.getAuthorizationOrganizeId());
        obj2.put("authorizationOrganizeNo", "");

        JSONArray array21 = new JSONArray();
        JSONObject obj21 = new JSONObject();
        obj21.put("docFilekey", contractFileKey);

        JSONArray array211 = new JSONArray();
        JSONObject obj211 = new JSONObject();
        obj211.put("addSignTime", false);
        obj211.put("edgePosition", 1);
        obj211.put("posPage", 2);
        obj211.put("sealId", companyEntity.getSealId());
        obj211.put("qrcodeSign", false);
        obj211.put("sealType", "1");
        obj211.put("posX", 100);
        obj211.put("posY", -25);
        obj211.put("key", "甲方");
        obj211.put("keyIndex", 100);
        obj211.put("signIdentity", "ORGANIZE");
        obj211.put("signType", 4);
        array211.add(obj211);

        JSONObject org = new JSONObject();
        org.put("addSignTime", false);
        org.put("edgePosition", 3);
        org.put("posPage", "1-" + 2);
        org.put("sealId", sealId);
        org.put("edgeScope", 0);
        org.put("posX", 0);
        org.put("posY", 200 * (0 + 1));
        org.put("signType", 3);
        array211.add(org);

        obj21.put("signPos", array211);
        array21.add(obj21);
        obj2.put("signDocDetails", array21);
        obj2.put("signOrder", 1);
        array2.add(obj2);

        JSONObject obj3 = new JSONObject();
        obj3.put("uniqueId", uniqueId);
        obj3.put("accountType", 2);
        obj3.put("autoSign", false);
        obj3.put("contactMobile", mobile);
        JSONArray array31 = new JSONArray();
        JSONObject obj31 = new JSONObject();
        obj31.put("docFilekey", contractFileKey);
        JSONArray array311 = new JSONArray();
        JSONObject obj311 = new JSONObject();
        obj311.put("addSignTime", false);
        obj311.put("posPage", 2);
        obj311.put("posX", 50);
        obj311.put("posY", 15);
        obj311.put("key", "乙方");
        obj311.put("keyIndex", 100);
        obj311.put("qrcodeSign", false);
        obj311.put("sealType", "0");
        obj311.put("signIdentity", "PERSON");
        obj311.put("signType", 4);
        obj311.put("width", 100);
        array311.add(obj311);

        JSONObject org1 = new JSONObject();
        org1.put("addSignTime", false);
        org1.put("edgePosition", 3);
        org1.put("posPage", "1-" + 2);
        org1.put("sealId", sealId);
        org1.put("edgeScope", 0);
        org1.put("posX", 0);
        org1.put("posY", 200 * (1 + 1));
        org1.put("signType", 3);
        array311.add(org1);

        obj31.put("signPos", array311);
        array31.add(obj31);
        obj3.put("signDocDetails", array31);
        obj3.put("signOrder", 2);
        array2.add(obj3);
        object.put("signers", array2);
        object.put("subject", "培训协议");


        String name = "培训协议";
        List<ContractOrgVo> orgVos = new ArrayList<>();
        List<ContractParamVo> personVo = new ArrayList<>();
        ContractOrgVo orgVo = new ContractOrgVo();
        orgVo.setNumber(2);
        orgVo.setOrganizeId(companyEntity.getAuthorizationOrganizeId());
        orgVo.setSealId(companyEntity.getSealId());
        String[] orgKeys = null;
        String[] orgPage = null;
        String[] personKeys = null;
        String[] personPages = null;
        orgKeys = "甲方".split(",");
        personKeys = "乙方".split(",");
        orgPage = "2".split(",");
        personPages = "2".split(",");
        List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
        orgVo.setParamList(paramVos);
        personVo = getParamList(personKeys, personPages, null);
        orgVos.add(orgVo);
        s = getBodyString(callProtocolBackUrl, mobile, idcard, contractFileKey, companyEntity.getInitiatorAccountId(), companyEntity.getInitiatorName(),
                companyEntity.getESignOrgId(), name, orgVos, personVo,new ArrayList<>());

        log.info("请求体是：{}", s);
        log.info("请求体是：{}", object.toJSONString());
//        开始盖企业章
        R<Map<String, Object>> sign = httpRest.sign(s);
        if (!sign.getFlag()) {
            return sign;
        }
        //企业盖章后返回流程id,
        String signUrl = (String) sign.getData().get("signUrl");
        Integer flowId = TypeCastUtils.toInt(sign.getData().get("docId"));
        log.info("合同流程id:{}", flowId);


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("signUrl", signUrl);

        protocolPersonnelEntity.setFlowId(flowId);
        protocolPersonnelEntity.setStatus(1);
        protocolPersonnelEntity.setIsSend(1);
        protocolPersonnelService.updateByIdE(protocolPersonnelEntity);
        //将签署协议地址发送邮件给员工
        String mail = employeeInfoEntity.getPrivatemail();
        asyncEmployeeMethod.sendEmail(mail, protocolPersonnelEntity.getOid(), signUrl, "彰泰集团：您有一份培训协议需要签署");
        return R.ok(jsonObject);
    }

    @PostMapping("/sendCertificate")
    @ApiOperation(value = "生成证明开据地址 ")
//    @SysAuthorityLog(value = "生成证明开据地址")
    public R sendCertificate(String id) throws Exception {
        CertificateEntity entity = certificateService.getByIdE(Long.parseLong(id));
        if (ObjectUtils.isEmpty(entity)) {
            return R.error();
        }
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectById(entity.getOid());
        String idcard = employeeInfoEntity.getIdcard();
        if (ObjectUtils.isEmpty(employeeInfoEntity)) {
            return R.error("根据id查询员工为空");
        }
        String realName = employeeInfoEntity.getName();
        if (StringUtils.isEmpty(realName)) {
            return R.error("新员工姓名不能为空");
        }
        if (StringUtils.isEmpty(idcard)) {
            return R.error("新员工身份证不能为空");
        }
        String mobile = employeeInfoEntity.getMobile();
        if (StringUtils.isEmpty(mobile)) {
            return R.error("新员工手机号不能为空");
        }
        //封装e签宝 创建外部用户所需要的参数
        OutSideAccountEntity outSideAccountEntity = getOutSideAccountEntity(realName, idcard, mobile, idcard);
        String uniqueId = idcard;
//        先根据唯一id查询外部用户是否已经创建
        R<String> outsideUser = httpRest.queryOutsideUser(uniqueId);
        if (outsideUser.getFlag()) {
            String s = outsideUser.getData();
            log.info("查询用户为：{}", s);
            uniqueId = s;
        } else {
            // 如果查不到用户，则调用e签宝接口创建外部用户
            R<String> outSideAccount = httpRest.createOutSideAccount(outSideAccountEntity);
            if (!outSideAccount.getFlag()) {
                return outSideAccount;
            }
        }
        ContractModelEntity modelEntity = contractModelDao.selectOne(new QueryWrapper<ContractModelEntity>().eq("id", entity.getModelId()).eq("is_delete", 0));
        if (ObjectUtils.isEmpty(modelEntity)) {
            return R.error("模板不存在！");
        }
        log.info("用户账号:{}", uniqueId);

        EmployerCompanyEntity companyEntity = employerCompanyService.getByIdE(entity.getCompanyId());
        //生成协议pdf
        R pdfR = contractPdf.createCertificatePdf(companyEntity, modelEntity, entity, employeeInfoEntity);
        if (!pdfR.getFlag()) {
            return pdfR;
        }
        String path = pdfR.getData().toString();
        //上传协议
        R<String> r = httpRest.upLoadNewPdf(path);
        if (!r.getFlag()) {
            return r;
        }
        // e签宝返回docKey
        String contractFileKey = r.getData();

        //        开始签合同
        String s = getCertificateParam("", modelEntity, companyEntity, mobile, contractFileKey, idcard);
        R<Map<String, Object>> sign = httpRest.sign(s);
        if (!sign.getFlag()) {
            return sign;
        }
        //企业盖章后返回流程id,
        String signUrl = (String) sign.getData().get("signUrl");
        Integer flowId = TypeCastUtils.toInt(sign.getData().get("docId"));
        log.info("合同流程id:{}", flowId);
        log.info("合同地址:{}", signUrl);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("signUrl", signUrl);

        entity.setFlowId(flowId);
        entity.setIsSend(1);
        entity.setCallbackStatus(0);
        certificateService.updateByIdE(entity);

//        //将签署协议地址发送邮件给员工
//        String mail = employeeInfoEntity.getPrivatemail();
//        asyncEmployeeMethod.sendEmail(mail, entity.getOid(), signUrl,"彰泰集团：您有一份收入证明");
        return R.ok(jsonObject);
    }

    /*
      签约培训协议回调地址
       */
    @PostMapping("/eSignCallProtocolBack")
    public R eSignCallProtocolBack(@RequestBody CallbackVo callbackVo) throws Exception {

        Integer flowId = callbackVo.getFlowId();

        String action = callbackVo.getAction();
        String createTime = callbackVo.getCreateTime();//签订时间
        if (callbackVo.getStatus().equals(2) && action.equals("SIGN_FLOW_FINISH")) {

            log.info("培训协议回调成功=====>>>:{}", callbackVo);

            protocolDoSign(flowId, createTime); //回调成功，回填合同地址，修改合同状态

        }
        return R.ok();
    }

    /**
     * 回填培训协议地址，修改合同状态
     *
     * @param flowId
     * @throws Exception
     */
    private void protocolDoSign(Integer flowId, String createTime) throws Exception {
        ProtocolPersonnelEntity protocolPersonnelEntity = protocolPersonnelDao.selectOne(new QueryWrapper<ProtocolPersonnelEntity>().eq("flow_id", flowId));
        protocolPersonnelEntity.setStatus(2); //将合同状态设置为已签署
        protocolPersonnelEntity.setCallBackStatus(1);
        String downloadDocUrl = httpRest.getContractUrl(flowId).getData();
        //添加签订时间
        protocolPersonnelEntity.setSignedDate(DateUtils.parseDateYMDHMSS(createTime));
        protocolPersonnelEntity.setContractEsignUrl(downloadDocUrl); //插入下载地址

        InputStream inputStream = IoUtils.getInputStreamByUrl(downloadDocUrl);
        EmployeeInfoEntity employeeInfoEntity = employeeInfoService.getByIdE(protocolPersonnelEntity.getOid());
        String upload = ossUploadService.upload(inputStream, "contract", employeeInfoEntity.getIdcard() + ".pdf");
        protocolPersonnelEntity.setContractOssUrl(upload);
        protocolPersonnelDao.updateById(protocolPersonnelEntity);
        List<ProtocolPersonnelEntity> protocolPersonnelEntityList = protocolPersonnelDao.selectList(new QueryWrapper<ProtocolPersonnelEntity>()
                .eq("protocol_id", protocolPersonnelEntity.getProtocolId()).and(i->i.eq("status", 0).or().eq("status", 1)));
        if (CollectionUtils.isEmpty(protocolPersonnelEntityList)) {
            ProtocolEntity protocolEntity = protocolService.getByIdE(protocolPersonnelEntity.getProtocolId());
            protocolEntity.setStatus(2);
            protocolService.updateByIdE(protocolEntity);
        }
    }


    /*
    签约回调地址
     */
    @PostMapping("/eSignCallBack")
    public R callBack(@RequestBody CallbackVo callbackVo) throws Exception {
        Integer flowId = callbackVo.getFlowId();
        log.info("开始回调：============>>>>>>{}", callbackVo);
        String action = callbackVo.getAction();
        String createTime = callbackVo.getCreateTime();//签订时间
        if (callbackVo.getStatus().equals(2) && action.equals("SIGN_FLOW_FINISH")) {
            ContractMangerEntity entity = contractMangerService.getByEsignId(flowId);
            log.info("签合同回调成功=======>>>>>>>>：{}", callbackVo);
            if (!ObjectUtils.isEmpty(entity)) {
                doSign(flowId, entity, createTime); //回填合同地址，修改合同状态
                return R.ok();
            }
        }
        return R.ok();
    }

    @PostMapping("/certificateCallBack")
    public R certificateCallBack(@RequestBody CallbackVo callbackVo) throws Exception {
        Integer flowId = callbackVo.getFlowId();
        log.info("开始回调：============>>>>>>{}", callbackVo);
        String action = callbackVo.getAction();
//        String createTime = callbackVo.getCreateTime();//签订时间
        if (callbackVo.getStatus().equals(2) && action.equals("SIGN_FLOW_FINISH")) {
            CertificateEntity entity = certificateService.getByEsignId(flowId);
            doCertificateSign(flowId, entity);
        }
        return R.ok();
    }

    private void handleEmployeeContract(Integer flowId, ContractMangerEntity entity, String createTime) {
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("esign_flow_id", flowId));
        if (!ObjectUtils.isEmpty(employeeInfoEntity)) {
            employeeInfoEntity.setIsSendContract(2); //将合同状态设置为已签署
            employeeInfoEntity.setContractBeginDate(entity.getContractBeginDate());
            employeeInfoEntity.setContractEndDate(entity.getContractEndDate());
            employeeInfoEntity.setEmployerCompanyId(entity.getEmployerCompanyId());
            employeeInfoEntity.setSignDate(DateUtils.parseDateYMDHMSS(createTime));
            employeeInfoDao.updateById(employeeInfoEntity);
            //更新待办通知状态
            if (!StringUtils.isEmpty(employeeInfoEntity.getOid())) {
                List<NoticeEntity> noticeList = noticeDao.selectList(new QueryWrapper<NoticeEntity>().eq("operation_id", employeeInfoEntity.getOid()).
                        eq("type", TodoConst.PRE_ENTRY));
                for (NoticeEntity noticeEntity : noticeList) {
                    noticeEntity.setIsDone(1);
                    noticeEntity.setDoneDate(new Date());
                    noticeDao.updateById(noticeEntity);
                }
            }
        }

    }


    @Transactional
    public void doSign(Integer flowId, ContractMangerEntity entity, String createTime) throws Exception {
        //更新劳动合同
        if (ContractConst.CONTRACT_MANGER_LAOB.equals(entity.getContractType())) {
            handleEmployeeContract(flowId, entity, createTime);
        }
        String downloadDocUrl = httpRest.getContractUrl(flowId).getData();
        //更新合同信息
        ContractFinishVo vo = new ContractFinishVo();
        vo.setDownloadDocUrl(downloadDocUrl);
        vo.setCreateTime(createTime);
        vo.setId(entity.getId());
//        contractMangerService.updateByIdE(entity);
        //已经签署过就不更新完结状态
        if (!entity.getIsSendContract().equals(2)) {
            contractController.finishContract(vo);

        }
    }

    @Transactional
    public void doCertificateSign(Integer flowId, CertificateEntity entity) {
        //更新劳动合同
        String downloadDocUrl = httpRest.getContractUrl(flowId).getData();
        EmployeeInfoEntity infoEntity = employeeInfoService.getByIdE(entity.getOid());
        entity.setContractEsignUrl(downloadDocUrl);
        entity.setContractOssUrl(contractController.uploadToOssAndUpdate(downloadDocUrl, infoEntity.getIdcard()));
        entity.setCallbackStatus(2);
        certificateService.updateByIdE(entity);
    }

    /**
     * @Description: 可以根据传入的值进行位置偏移
     * @params 增加offsetList列表
     * @Author: czw
     * @return 
     * @CreateDate: 2021/3/15 17:14
     */
    public String getBodyString(String callBackUrl, String mobile, String uniqueId, String contractFileKey, String initiatorAccountId,
                                String initiatorName, String eSignOrgId, String name, List<ContractOrgVo> orgList, List<ContractParamVo> personList,List<ContractPositionVo> offsetList) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("callbackUrl", callBackUrl);
        jsonObject.put("initiatorAccountId", initiatorAccountId);
        jsonObject.put("initiatorName", initiatorName);
        jsonObject.put("initiatorOrganizeId", eSignOrgId);
        jsonObject.put("redirectUrl", "");
        JSONArray signDocs = new JSONArray();
        JSONObject doc = new JSONObject();
        doc.put("docFilekey", contractFileKey);
        doc.put("docName", name);
        signDocs.add(doc);
        jsonObject.put("signDocs", signDocs);
        JSONArray signers = new JSONArray();
        JSONObject personSigner = personSinger(uniqueId, mobile, contractFileKey, personList,offsetList);
        int i = 0;
        for (ContractOrgVo orgVo : orgList) {
            JSONObject orgSigner = orgSinger(contractFileKey, orgVo.getParamList(), orgVo.getSealId(),
                    initiatorAccountId, orgVo.getOrganizeId(), orgVo.getNumber(), i);
            signers.add(orgSigner);
            i++;
        }
        if (!ObjectUtils.isEmpty(personSigner)) {
            signers.add(personSigner);
        }
        jsonObject.put("signers", signers);
        jsonObject.put("subject", name);
        return jsonObject.toString();
    }

    private JSONObject personSinger(String uniqueId, String mobile, String contractFileKey, List<ContractParamVo> personList,List<ContractPositionVo> offsetList) {
        if (CollectionUtils.isEmpty(personList) || personList.size() == 0) {
            return null;
        }
        //个人签
        JSONObject personSigner = new JSONObject();
        personSigner.put("uniqueId", uniqueId);
        personSigner.put("accountType", 2);
        personSigner.put("autoSign", false);
        personSigner.put("contactMobile", mobile);
        personSigner.put("signOrder", "2");
        JSONArray personDetails = new JSONArray();
        JSONObject personDetail = new JSONObject();
        personDetail.put("docFilekey", contractFileKey);
        JSONArray personPos = new JSONArray();
        for (ContractParamVo personParam : personList) {
            JSONObject person = new JSONObject();
            person.put("addSignTime", false);
            person.put("posPage", personParam.getPage());

            if(offsetList.size() > 0){
                Optional<ContractPositionVo> cpv = offsetList.stream() .filter(t -> t.getPage().equals(personParam.getPage())) .findFirst();
                if (cpv.isPresent()) {
                    ContractPositionVo cp = cpv.get();
                    String type = cp.getPosType();
                    person.put(type, cp.getNum());
                    if(type.equals("posX")){
                        person.put("posY", 25);
                    }else{
                        person.put("posX", 100);
                    }
                }else{
                    person.put("posX", 100);
                    person.put("posY", 25);
                }
            }else{
                person.put("posX", 100);
                person.put("posY", 25);
            }

            person.put("sealType", "0");
            person.put("key", personParam.getKey());
            person.put("keyIndex", 100);
            person.put("qrcodeSign", false);
            person.put("signType", 4);
            person.put("signIdentity", "PERSON");
            person.put("width", 100);
            personPos.add(person);
        }

        personDetail.put("signPos", personPos);
        personDetails.add(personDetail);
        personSigner.put("signDocDetails", personDetails);
        return personSigner;
    }

    private JSONObject orgSinger(String contractFileKey, List<ContractParamVo> orgList,
                                 String sealId, String initiatorAccountId,
                                 String authorizationOrganizeId, Integer number, int i) {
        //公司签章
        JSONObject orgSigner = new JSONObject();
        orgSigner.put("accountId", initiatorAccountId);
        orgSigner.put("accountType", 1);
        orgSigner.put("autoSign", true);
        orgSigner.put("authorizationOrganizeId", authorizationOrganizeId);
        orgSigner.put("authorizationOrganizeNo", "");
        orgSigner.put("signOrder", "1");
        JSONArray orgDetails = new JSONArray();
        JSONObject orgDetail = new JSONObject();
        orgDetail.put("docFilekey", contractFileKey);
        JSONArray orgPos = new JSONArray();
        Boolean flag = true;
        for (ContractParamVo orgParam : orgList) {
            JSONObject org = new JSONObject();
            org.put("addSignTime", false);
            org.put("edgePosition", 1);
            org.put("posPage", orgParam.getPage());
            org.put("sealId", sealId);
            org.put("qrcodeSign", false);
            org.put("sealType", "1");
            org.put("key", orgParam.getKey());
            if (ObjectUtils.isEmpty(orgParam.getIndex())) {
                org.put("keyIndex", 100);
            } else {
                org.put("keyIndex", orgParam.getIndex());
            }
            if(orgParam.getKey().equals("第一联")){
                org.put("posX", -125);
                org.put("posY", -25);
                flag = false;
            }

            org.put("signIdentity", "ORGANIZE");
            org.put("signType", 4);
            orgPos.add(org);
        }
        //骑缝章(总页数不为1添加骑缝章)
        if (number != 1 && flag) {
            JSONObject org = new JSONObject();
            org.put("addSignTime", false);
            org.put("edgePosition", 3);
            org.put("posPage", "1-" + number);
            org.put("sealId", sealId);
            org.put("edgeScope", 0);
            org.put("posX", 0);
            org.put("posY", 200 * (i + 1));
            org.put("signType", 3);
            orgPos.add(org);
        }

        orgDetail.put("signPos", orgPos);
        orgDetails.add(orgDetail);
        orgSigner.put("signDocDetails", orgDetails);
        return orgSigner;
    }

    /**
     * 新签各类合同参数
     *
     * @param s
     * @param modelEntity
     * @param companyEntity
     * @param mobile
     * @param contractFileKey
     * @param idcard
     * @param serverEntity
     * @return
     */
    private String getNewContractParam(String s, ContractModelEntity modelEntity, EmployerCompanyEntity companyEntity,
                                       String mobile, String contractFileKey, String idcard, EmployerCompanyEntity serverEntity) {
        String name = "劳动合同";
        List<ContractOrgVo> orgVos = new ArrayList<>();
        List<ContractParamVo> personVo = new ArrayList<>();
        List<ContractPositionVo> offsetList = new ArrayList<>();
        ContractOrgVo orgVo = new ContractOrgVo();
        orgVo.setNumber(modelEntity.getContractNumber());
        orgVo.setOrganizeId(companyEntity.getAuthorizationOrganizeId());
        orgVo.setSealId(companyEntity.getSealId());
        //地产及子公司M1及P4以上无亲属报备
        if (modelEntity.getDetailType().equals("1")) {
            String[] orgKeys = "单位,甲,盖章,签章,甲方".split(",");
            String[] orgPage = "1,23,5,11,13".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "签收人,承诺人,乙方：,乙方,乙方,承诺人签名：,人：,人：,名：,名：".split(",");
            String[] personPages = "1,2,11,13,23,28,42,43,44,45".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
        }
        //地产及子公司M1及P4以上有亲属报备
        else if (modelEntity.getDetailType().equals("2")) {
            String[] orgKeys = "单位,甲,盖章,签章,甲方".split(",");
            String[] orgPage = "1,23,5,11,13".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "签收人,报备人,乙方：,乙方,乙方,承诺人签名：,承诺人：,人：,名：,名：".split(",");
            String[] personPages = "1,2,11,13,23,28,42,43,44,45".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);

        }
        //地产及子公司P3以下无亲属报备
        else if (modelEntity.getDetailType().equals("3")) {
            String[] orgKeys = "单位,甲,盖章,签章,甲方".split(",");
            String[] orgPage = "1,22,5,10,12".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "签收人,承诺人,乙方：,乙方,乙方,承诺人签名：,承诺人：,人：,名：,名：".split(",");
            String[] personPages = "1,2,10,12,22,27,41,42,43,44".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(170).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(12).num(170).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(22).num(190).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(27).num(220).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(42).num(160).build());
        }
        //地产及子公司P3以下有亲属报备
        else if (modelEntity.getDetailType().equals("4")) {
            String[] orgKeys = "单位,甲,盖章,签章,甲方".split(",");
            String[] orgPage = "1,22,5,10,12".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "签收人,报备人：,乙方,乙方,乙方,承诺人签名：,人：,人：,名：,名：".split(",");
            String[] personPages = "1,2,10,12,22,27,41,42,43,44".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);

        }
        //小微公司P3以下-无亲属报备
        else if (modelEntity.getDetailType().equals("5")) {
            ContractOrgVo serverVo = new ContractOrgVo();
            serverVo.setSealId(serverEntity.getSealId());
            serverVo.setOrganizeId(serverEntity.getAuthorizationOrganizeId());
            String[] serverKeys = "盖章,签章,甲方".split(",");
            String[] serverPage = "5,10,12".split(",");
            List<ContractParamVo> serverVos = getParamList(serverKeys, serverPage, null);
            String[] orgKeys = "盖章,甲".split(",");
            String[] orgPage = "1,22".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            serverVo.setParamList(serverVos);
            serverVo.setNumber(modelEntity.getContractNumber());
            String[] personKeys = "签收人：,承诺人,乙方：,方：,乙方,承诺人姓名,人：,承诺人：,名".split(",");
            String[] personPages = "1,2,10,12,22,27,40,41,42".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            orgVos.add(serverVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(1).num(435).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(175).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(12).num(140).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(22).num(175).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(40).num(60).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(41).num(390).build());
        }
        //小微公司P3以下-有亲属报备
        else if (modelEntity.getDetailType().equals("6")) {
            ContractOrgVo serverVo = new ContractOrgVo();
            serverVo.setSealId(serverEntity.getSealId());
            serverVo.setOrganizeId(serverEntity.getAuthorizationOrganizeId());
            String[] serverKeys = "盖章,签章,甲方".split(",");
            String[] serverPage = "5,10,12".split(",");
            List<ContractParamVo> serverVos = getParamList(serverKeys, serverPage, null);
            String[] orgKeys = "盖章,甲".split(",");
            String[] orgPage = "1,22".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            serverVo.setParamList(serverVos);
            serverVo.setNumber(modelEntity.getContractNumber());
            String[] personKeys = "签收人,承诺人：,乙方：,方：,乙方,承诺人姓名,人：,承诺人：,名".split(",");
            String[] personPages = "1,2,10,12,22,27,40,41,42".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            orgVos.add(serverVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(1).num(435).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(175).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(12).num(140).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(22).num(175).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(40).num(140).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(41).num(390).build());
        }
        //小微公司M1及P4以上-无亲属报备
        else if (modelEntity.getDetailType().equals("31")) {
            ContractOrgVo serverVo = new ContractOrgVo();
            serverVo.setSealId(serverEntity.getSealId());
            serverVo.setOrganizeId(serverEntity.getAuthorizationOrganizeId());
            String[] serverKeys = "盖章,签章,甲方".split(",");
            String[] serverPage = "5,11,13".split(",");
            List<ContractParamVo> serverVos = getParamList(serverKeys, serverPage, null);
            String[] orgKeys = "盖章,甲".split(",");
            String[] orgPage = "1,23".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            serverVo.setParamList(serverVos);
            serverVo.setNumber(modelEntity.getContractNumber());
            String[] personKeys = "签收人,承诺人,乙方：,方：,乙方,承诺人姓名,人：,承诺人：,名".split(",");
            String[] personPages = "1,2,11,13,23,28,41,42,43".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            orgVos.add(serverVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(1).num(445).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(2).num(95).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(11).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(13).num(155).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(23).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(28).num(125).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(41).num(145).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(42).num(395).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(43).num(75).build());
        }
        //小微公司M1及P4以上-有亲属报备
        else if (modelEntity.getDetailType().equals("32")) {
            ContractOrgVo serverVo = new ContractOrgVo();
            serverVo.setSealId(serverEntity.getSealId());
            serverVo.setOrganizeId(serverEntity.getAuthorizationOrganizeId());
            String[] serverKeys = "盖章,签章,签章".split(",");
            String[] serverPage = "5,11,13".split(",");
            List<ContractParamVo> serverVos = getParamList(serverKeys, serverPage, null);
            String[] orgKeys = "盖章,甲".split(",");
            String[] orgPage = "1,23".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            serverVo.setParamList(serverVos);
            serverVo.setNumber(modelEntity.getContractNumber());
            String[] personKeys = "签收人,乙方：,方：,乙方,承诺人姓名：,人：,承诺人：,名".split(",");
            String[] personPages = "1,11,13,23,28,41,42,43".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            orgVos.add(serverVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(1).num(85).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(11).num(185).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(13).num(155).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(23).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(28).num(120).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(41).num(80).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(42).num(400).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(43).num(65).build());
        }
        //实习协议
        else if (modelEntity.getDetailType().equals("8")) {
            String[] orgKeys = "甲方：".split(",");
            String[] orgPage = "1".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            String[] personKeys = "乙方：".split(",");
            String[] personPages = "1".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVo.setParamList(paramVos);
            orgVos.add(orgVo);
        } else {
            String[] orgKeys = "代表人".split(",");
            String[] orgPage = "4".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "方：".split(",");
            String[] personPages = "4".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            name = "返聘协议";

        }
        s = getBodyString(callBackUrl, mobile, idcard, contractFileKey, companyEntity.getInitiatorAccountId(), companyEntity.getInitiatorName(),
                companyEntity.getESignOrgId(), name, orgVos, personVo,offsetList);
        return s;
    }

    /**
     * 培训协议回调补偿
     *
     * @return
     * @throws Exception
     */
    public void checkProtocolContractStatus() throws Exception {
        List<ProtocolPersonnelEntity> ProtocolPersonnelEntities = protocolPersonnelDao.selectList(new QueryWrapper<ProtocolPersonnelEntity>().eq("call_back_status", 0).eq("is_delete", 0));
        if (!CollectionUtils.isEmpty(ProtocolPersonnelEntities)) {
            for (ProtocolPersonnelEntity protocolPersonnelEntity : ProtocolPersonnelEntities) {
                Integer flowId = protocolPersonnelEntity.getFlowId();
                R signDetail = httpRest.getSignDetail(flowId); //查询为成功的 才更新
                if (signDetail.getFlag()) {
                    JSONObject json = (JSONObject) signDetail.getData();
                    Date signTime = new Date();
                    JSONArray singers = json.getJSONArray("signers");
                    for (int i = 0; i < singers.size(); i++) {
                        JSONObject s = singers.getJSONObject(i);
                        String singer = s.getString("accountType");
                        if ("2".equals(singer)) {
                            signTime = s.getDate("signTime");
                            break;
                        }
                    }
                    protocolDoSign(flowId, DateUtils.format(signTime, "yyyy-MM-dd hh:mm:ss"));
                }
            }
        }
    }

    /**
     * 新合同回调补偿
     *
     * @return
     * @throws Exception
     */
    public void checkContractStatus() throws Exception {
        List<ContractMangerEntity> entityList = contractMangerDao.selectList(new QueryWrapper<ContractMangerEntity>().eq("callback_status", 0).eq("is_delete", 0));
        if (!CollectionUtils.isEmpty(entityList)) {
            for (ContractMangerEntity contractUrlEntity : entityList) {
                Integer flowId = contractUrlEntity.getEsignFlowId();
                R signDetail = httpRest.getSignDetail(flowId); //查询为成功的 才更新
                if (signDetail.getFlag()) {
                    JSONObject json = (JSONObject) signDetail.getData();
                    Date signTime = new Date();
                    JSONArray singers = json.getJSONArray("signers");
                    for (int i = 0; i < singers.size(); i++) {
                        JSONObject s = singers.getJSONObject(i);
                        String singer = s.getString("accountType");
                        if ("2".equals(singer)) {
                            signTime = s.getDate("signTime");
                            break;
                        }
                    }
                    doSign(flowId, contractUrlEntity, DateUtils.format(signTime, "yyyy-MM-dd hh:mm:ss"));
                }
                //签约失败的设置为未发送状态
                else {
                    contractUrlEntity.setContractStatus(0);
                    contractUrlEntity.setCallbackStatus(2);
                    contractMangerDao.updateById(contractUrlEntity);
                }
            }
        }
    }

    public void checkCertificate() {
        List<CertificateEntity> entityList = certificateService.getCertificateUnCallBack();
        if (!CollectionUtils.isEmpty(entityList)) {
            for (CertificateEntity entity : entityList) {
                Integer flowId = entity.getFlowId();
                R signDetail = httpRest.getSignDetail(flowId); //查询为成功的 才更新
                if (signDetail.getFlag()) {
                    doCertificateSign(flowId, entity);
                } else {
                    entity.setCallbackStatus(2);
                    certificateService.updateByIdE(entity);
                }
            }
        }
    }


    /**
     * 续签各类合同参数
     *
     * @param s
     * @param modelEntity
     * @param companyEntity
     * @param mobile
     * @param contractFileKey
     * @param idcard
     * @param serverEntity
     * @return
     */
    private String getReNewContractParam(String s, ContractModelEntity modelEntity, EmployerCompanyEntity companyEntity,
                                         String mobile, String contractFileKey, String idcard, EmployerCompanyEntity serverEntity) {
        String name = "劳动合同续签";
        List<ContractOrgVo> orgVos = new ArrayList<>();
        List<ContractParamVo> personVo = new ArrayList<>();
        List<ContractPositionVo> offsetList = new ArrayList<>();
        ContractOrgVo orgVo = new ContractOrgVo();
        orgVo.setNumber(modelEntity.getContractNumber());
        orgVo.setOrganizeId(companyEntity.getAuthorizationOrganizeId());
        orgVo.setSealId(companyEntity.getSealId());
        //地产及子公司M1及P4以上固定期限续签
        if (modelEntity.getDetailType().equals("10")) {
            String[] orgKeys = "代表,甲方,盖章,甲方".split(",");
            String[] orgPage = "10,16,19,40".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "乙方：,乙方：,承诺人签名：,承诺人：,乙方：,名:".split(",");
            String[] personPages = "10,16,24,38,40,41".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(205).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(16).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(24).num(235).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(40).num(195).build());
        }
        //地产及子公司M1及P4以上无固定期限续签
        else if (modelEntity.getDetailType().equals("11")) {
            String[] orgKeys = "代表,甲方,盖章,甲方".split(",");
            String[] orgPage = "10,16,19,40".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "乙方：,乙方：,承诺人签名：,承诺人：,乙方：,名:".split(",");
            String[] personPages = "10,16,24,38,40,41".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(205).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(16).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(24).num(235).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(40).num(195).build());
        }
        //地产及子公司P3以下无固定期限续签
        else if (modelEntity.getDetailType().equals("12")) {
            String[] orgKeys = "代表,盖章,签章,甲方".split(",");
            String[] orgPage = "10,13,18,39".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "乙方：,乙方：,承诺人签名：,承诺人：,乙方：,名:".split(",");
            String[] personPages = "10,18,23,37,39,40".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(205).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(18).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(23).num(235).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(39).num(195).build());
        }
        //地产及子公司P3以下固定期限续签
        else if (modelEntity.getDetailType().equals("13")) {
            String[] orgKeys = "代表,甲方,盖章,甲方".split(",");
            String[] orgPage = "10,15,18,39".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "乙方：,乙方：,承诺人签名：,承诺人：,乙方：,名:".split(",");
            String[] personPages = "10,15,23,37,39,40".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(205).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(15).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(23).num(235).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(39).num(195).build());
        }
        //小微公司P3以下-无固定期限续签
        else if (modelEntity.getDetailType().equals("15")) {
            ContractOrgVo serverVo = new ContractOrgVo();
            serverVo.setSealId(serverEntity.getSealId());
            serverVo.setOrganizeId(serverEntity.getAuthorizationOrganizeId());
            String[] serverKeys = "签章,盖章,签章".split(",");
            String[] serverPage = "15,18,39".split(",");
            List<ContractParamVo> serverVos = getParamList(serverKeys, serverPage, null);
            String[] orgKeys = "甲".split(",");
            String[] orgPage = "10".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            serverVo.setNumber(modelEntity.getContractNumber());
            serverVo.setParamList(serverVos);
            String[] personKeys = "乙方：,乙方：,承诺人姓名：,人：,承诺人：,方：,名:".split(",");
            String[] personPages = "10,15,23,36,37,39,40".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            orgVos.add(serverVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(15).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(23).num(235).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(36).num(155).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(37).num(415).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(39).num(165).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(40).num(75).build());
        }
        //小微公司P3以下-固定期限续签
        else if (modelEntity.getDetailType().equals("16")) {
            ContractOrgVo serverVo = new ContractOrgVo();
            //彰泰集团签章关键字
            String[] serverKeys = "签章,盖章,签章".split(",");
            //彰泰集团签章页码
            String[] serverPage = "15,18,39".split(",");
            List<ContractParamVo> serverVos = getParamList(serverKeys, serverPage, null);
            //小微公司签章关键字
            String[] orgKeys = "甲".split(",");
            //小微公司签章页码
            String[] orgPage = "10".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            serverVo.setSealId(serverEntity.getSealId());
            serverVo.setOrganizeId(serverEntity.getAuthorizationOrganizeId());
            serverVo.setNumber(modelEntity.getContractNumber());
            serverVo.setParamList(serverVos);
            //给人签字位置
            String[] personKeys = "乙方：,乙方：,承诺人姓名：,人：,承诺人：,方：,名:".split(",");
            //给人签字页码
            String[] personPages = "10,15,23,36,37,39,40".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            orgVos.add(serverVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(15).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(23).num(235).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(36).num(155).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(37).num(415).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(39).num(165).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(40).num(75).build());
        }
        //小微公司P4以上-无固定期限续签
        else if (modelEntity.getDetailType().equals("33")) {
            ContractOrgVo serverVo = new ContractOrgVo();
            serverVo.setSealId(serverEntity.getSealId());
            serverVo.setOrganizeId(serverEntity.getAuthorizationOrganizeId());
            String[] serverKeys = "签章,盖章,签章".split(",");
            String[] serverPage = "16,19,40".split(",");
            List<ContractParamVo> serverVos = getParamList(serverKeys, serverPage, null);
            String[] orgKeys = "甲".split(",");
            String[] orgPage = "10".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            serverVo.setNumber(modelEntity.getContractNumber());
            serverVo.setParamList(serverVos);
            String[] personKeys = "乙方：,乙方：,承诺人姓名：,人：,承诺人：,方：,名:".split(",");
            String[] personPages = "10,16,24,37,38,40,41".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            orgVos.add(serverVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(16).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(24).num(235).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(37).num(75).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(38).num(405).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(40).num(155).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(41).num(75).build());
        }
        //小微公司P4以上-固定期限续签
        else if (modelEntity.getDetailType().equals("34")) {
            ContractOrgVo serverVo = new ContractOrgVo();
            String[] serverKeys = "签章,盖章,签章".split(",");
            String[] serverPage = "16,19,40".split(",");
            List<ContractParamVo> serverVos = getParamList(serverKeys, serverPage, null);
            String[] orgKeys = "甲".split(",");
            String[] orgPage = "10".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            serverVo.setSealId(serverEntity.getSealId());
            serverVo.setOrganizeId(serverEntity.getAuthorizationOrganizeId());
            serverVo.setNumber(modelEntity.getContractNumber());
            serverVo.setParamList(serverVos);
            String[] personKeys = "乙方：,乙方：,承诺人姓名：,人：,承诺人：,方：,名:".split(",");
            String[] personPages = "10,16,24,37,38,40,41".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            orgVos.add(serverVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(16).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(24).num(125).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(37).num(75).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(38).num(405).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(40).num(155).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(41).num(75).build());
        }
        //实习协议续签
        else if (modelEntity.getDetailType().equals("17")) {
            String[] orgKeys = "甲方：".split(",");
            String[] orgPage = "1".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            String[] personKeys = "乙方：,名:".split(",");
            String[] personPages = "1,2".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVo.setParamList(paramVos);
            orgVos.add(orgVo);
            name = "实习协议续签";
        } else {
            String[] orgKeys = "代表人".split(",");
            String[] orgPage = "4".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "方：,名:".split(",");
            String[] personPages = "4,5".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            name = "返聘协议续签";

        }
        s = getBodyString(callBackUrl, mobile, idcard, contractFileKey, companyEntity.getInitiatorAccountId(), companyEntity.getInitiatorName(),
                companyEntity.getESignOrgId(), name, orgVos, personVo,offsetList);
        return s;
    }


    /**
     * 调动新签各类合同参数
     *
     * @param s
     * @param modelEntity
     * @param companyEntity
     * @param mobile
     * @param contractFileKey
     * @param idcard
     * @param serverEntity
     * @return
     */
    private String getTransferContractParam(String s, ContractModelEntity modelEntity, EmployerCompanyEntity companyEntity,
                                            String mobile, String contractFileKey, String idcard, EmployerCompanyEntity serverEntity) {
        String name = "劳动合同调动签";
        List<ContractOrgVo> orgVos = new ArrayList<>();
        List<ContractParamVo> personVo = new ArrayList<>();
        List<ContractPositionVo> offsetList = new ArrayList<>();
        ContractOrgVo orgVo = new ContractOrgVo();
        orgVo.setNumber(modelEntity.getContractNumber());
        orgVo.setOrganizeId(companyEntity.getAuthorizationOrganizeId());
        orgVo.setSealId(companyEntity.getSealId());
        //地产及子公司M1及P4以上试用期调动新签
        if (modelEntity.getDetailType().equals("18")) {
            String[] orgKeys = "代表,甲方,盖章,盖章,甲方".split(",");
            String[] orgPage = "10,16,17,20,42".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "乙方：,乙方：,签收人：,承诺人签名,承诺人,人：,乙方：,名:".split(",");
            String[] personPages = "10,16,17,25,39,40,42,43".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(205).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(16).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(25).num(235).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(40).num(175).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(42).num(195).build());
        }
        //地产及子公司M1及P4以上非试用期调动新签
        else if (modelEntity.getDetailType().equals("19")) {
            String[] orgKeys = "代表,甲方,盖章,甲方".split(",");
            String[] orgPage = "10,16,19,41".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "乙方：,乙方：,承诺人签名,承诺人,人：,乙方：,名:".split(",");
            String[] personPages = "10,16,24,38,39,41,42".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(205).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(16).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(24).num(235).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(39).num(175).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(41).num(195).build());
        }
        //地产及子公司P3以下试用期调动新签
        else if (modelEntity.getDetailType().equals("20")) {
            String[] orgKeys = "代表,甲方,盖章,盖章,甲方".split(",");
            String[] orgPage = "10,15,16,19,41".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "乙方：,乙方：,签收人：,承诺人签名,承诺人,人：,乙方：,名:".split(",");
            String[] personPages = "10,15,16,24,38,39,41,42".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(205).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(15).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(24).num(235).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(39).num(175).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(41).num(195).build());
        }
        //地产及子公司P3以下非试用期调动新签
        else if (modelEntity.getDetailType().equals("21")) {
            String[] orgKeys = "代表,甲方,盖章,甲方".split(",");
            String[] orgPage = "10,15,18,40".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "乙方：,乙方：,承诺人签名,承诺人,人：,乙方：,名:".split(",");
            String[] personPages = "10,15,23,37,38,40,41".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(205).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(15).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(23).num(235).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(38).num(175).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(40).num(195).build());
        }
        //小微公司P3以下-试用期调动新签
        else if (modelEntity.getDetailType().equals("22")) {
            ContractOrgVo serverVo = new ContractOrgVo();
            String[] serverKeys = "签章,盖章,签章".split(",");
            String[] serverPage = "15,19,40".split(",");
            List<ContractParamVo> serverVos = getParamList(serverKeys, serverPage, null);
            String[] orgKeys = "甲,盖章".split(",");
            String[] orgPage = "10,16".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            serverVo.setParamList(serverVos);
            serverVo.setSealId(serverEntity.getSealId());
            serverVo.setNumber(modelEntity.getContractNumber());
            serverVo.setOrganizeId(serverEntity.getAuthorizationOrganizeId());
            String[] personKeys = ("乙方：,乙方：,人：,名：,人：,人：,方：,名:").split(",");
            String[] personPages = "10,15,16,24,37,38,40,41".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            orgVos.add(serverVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(15).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(16).num(175).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(24).num(105).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(37).num(155).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(38).num(225).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(40).num(155).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(41).num(75).build());
        }
        //小微公司P3以下-非试用期调动新签
        else if (modelEntity.getDetailType().equals("23")) {
            ContractOrgVo serverVo = new ContractOrgVo();
            serverVo.setSealId(serverEntity.getSealId());
            serverVo.setOrganizeId(serverEntity.getAuthorizationOrganizeId());
            String[] serverKeys = "签章,盖章,签章".split(",");
            String[] serverPage = "15,18,39".split(",");
            List<ContractParamVo> serverVos = getParamList(serverKeys, serverPage, null);
            String[] orgKeys = "甲".split(",");
            String[] orgPage = "10".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            serverVo.setParamList(serverVos);
            serverVo.setNumber(modelEntity.getContractNumber());
            String[] personKeys = "乙方：,乙方：,承诺人姓名：,人：,人：,方：,名:".split(",");
            String[] personPages = "10,15,23,36,37,39,40".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            orgVos.add(serverVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(15).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(23).num(125).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(36).num(75).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(37).num(225).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(39).num(155).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(40).num(75).build());
        }
        //小微公司P4以上-试用期调动新签
        else if (modelEntity.getDetailType().equals("35")) {
            ContractOrgVo serverVo = new ContractOrgVo();
            String[] serverKeys = "签章,盖章,签章".split(",");
            String[] serverPage = "16,20,41".split(",");
            List<ContractParamVo> serverVos = getParamList(serverKeys, serverPage, null);
            String[] orgKeys = "甲,盖章,盖章".split(",");
            String[] orgPage = "10,17,20".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            serverVo.setParamList(serverVos);
            serverVo.setSealId(serverEntity.getSealId());
            serverVo.setNumber(modelEntity.getContractNumber());
            serverVo.setOrganizeId(serverEntity.getAuthorizationOrganizeId());
            String[] personKeys = "乙方：,乙方：,人：,承诺人姓名,人：,人：,方：,名:".split(",");
            String[] personPages = "10,16,17,25,38,39,41,42".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            orgVos.add(serverVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(195).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(16).num(185).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(17).num(185).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(25).num(115).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(38).num(75).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(39).num(65).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(41).num(155).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(42).num(125).build());
        }
        //小微公司P4以上-非试用期调动新签
        else if (modelEntity.getDetailType().equals("36")) {
            ContractOrgVo serverVo = new ContractOrgVo();
            serverVo.setSealId(serverEntity.getSealId());
            serverVo.setOrganizeId(serverEntity.getAuthorizationOrganizeId());
            String[] serverKeys = "签章,盖章,签章".split(",");
            String[] serverPage = "16,19,40".split(",");
            List<ContractParamVo> serverVos = getParamList(serverKeys, serverPage, null);
            String[] orgKeys = "甲".split(",");
            String[] orgPage = "10".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            serverVo.setParamList(serverVos);
            serverVo.setNumber(modelEntity.getContractNumber());
            String[] personKeys = "乙方：,乙方：,承诺人姓名,人：,人：,方：,名:".split(",");
            String[] personPages = "10,16,24,37,38,40,41".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            orgVos.add(serverVo);
            offsetList.add(ContractPositionVo.builder().posType("posX").page(10).num(185).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(16).num(185).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(24).num(115).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(37).num(75).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(38).num(225).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(40).num(155).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(41).num(75).build());
        }
        //实习协议续签
        else if (modelEntity.getDetailType().equals("24")) {
            String[] orgKeys = "甲方：".split(",");
            String[] orgPage = "1".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            String[] personKeys = "乙方：,名:".split(",");
            String[] personPages = "1,2".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVo.setParamList(paramVos);
            orgVos.add(orgVo);
            name = "实习协议调动签";
        } else {
            String[] orgKeys = "代表人".split(",");
            String[] orgPage = "4".split(",");
            List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
            orgVo.setParamList(paramVos);
            String[] personKeys = "方：,名:".split(",");
            String[] personPages = "4,5".split(",");
            personVo = getParamList(personKeys, personPages, null);
            orgVos.add(orgVo);
            name = "返聘协议调动签";

        }
        s = getBodyString(callBackUrl, mobile, idcard, contractFileKey, companyEntity.getInitiatorAccountId(), companyEntity.getInitiatorName(),
                companyEntity.getESignOrgId(), name, orgVos, personVo,offsetList);
        return s;
    }

    public String getTerminate(String s, ContractModelEntity modelEntity, EmployerCompanyEntity companyEntity,
                               String mobile, String contractFileKey, String idcard, EmployerCompanyEntity serverEntity) {
        String name = "合同解除协议";
        List<ContractOrgVo> orgVos = new ArrayList<>();
        List<ContractParamVo> personVo = new ArrayList<>();
        List<ContractPositionVo> offsetList = new ArrayList<>();
        ContractOrgVo orgVo = new ContractOrgVo();
        orgVo.setNumber(modelEntity.getContractNumber());
        orgVo.setOrganizeId(companyEntity.getAuthorizationOrganizeId());
        orgVo.setSealId(companyEntity.getSealId());
        String[] orgKeys = null;
        String[] orgPage = null;
        String[] index = null;
        String[] personKeys = null;
        String[] personPages = null;
        if (modelEntity.getDetailType().equals("26")) {
            orgKeys = "代表人".split(",");
            orgPage = "1".split(",");
            personKeys = "方：".split(",");
            personPages = "1".split(",");
            offsetList.add(ContractPositionVo.builder().posType("posX").page(1).num(145).build());
        } else {
            orgKeys = "或,有限,第一联,有限".split(",");
            orgPage = "1,2,2,2".split(",");
            index = "100,1,2,2".split(",");
            personKeys = "方：,签收".split(",");
            personPages = "1,2".split(",");
            offsetList.add(ContractPositionVo.builder().posType("posX").page(1).num(145).build());
            offsetList.add(ContractPositionVo.builder().posType("posX").page(2).num(85).build());
        }
        List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, index);
        orgVo.setParamList(paramVos);
        personVo = getParamList(personKeys, personPages, null);
        orgVos.add(orgVo);
        s = getBodyString(callBackUrl, mobile, idcard, contractFileKey, companyEntity.getInitiatorAccountId(), companyEntity.getInitiatorName(),
                companyEntity.getESignOrgId(), name, orgVos, personVo,offsetList);
        return s;
    }

    private String getCertificateParam(String s, ContractModelEntity modelEntity, EmployerCompanyEntity companyEntity,
                                       String mobile, String contractFileKey, String idcard) {
        String name = "收入证明";
        List<ContractOrgVo> orgVos = new ArrayList<>();
        List<ContractParamVo> personVo = new ArrayList<>();
        ContractOrgVo orgVo = new ContractOrgVo();
        orgVo.setNumber(1);
        orgVo.setOrganizeId(companyEntity.getAuthorizationOrganizeId());
        orgVo.setSealId(companyEntity.getSealId());
        String[] orgKeys = null;
        String[] orgPage = null;
        String[] personKeys = null;
        String[] personPages = null;
        if (modelEntity.getDetailType().equals("30")) {
            orgKeys = "签章".split(",");
        } else {
            orgKeys = "盖章".split(",");
        }
        orgPage = "1".split(",");
        List<ContractParamVo> paramVos = getParamList(orgKeys, orgPage, null);
        orgVo.setParamList(paramVos);
        personVo = getParamList(personKeys, personPages, null);
        orgVos.add(orgVo);
        s = getBodyString(certificateCallBackUrl, mobile, idcard, contractFileKey, companyEntity.getInitiatorAccountId(), companyEntity.getInitiatorName(),
                companyEntity.getESignOrgId(), name, orgVos, personVo,new ArrayList<>());
        return s;
    }

    private List<ContractParamVo> getParamList(String[] keys, String[] pages, String[] index) {
        List<ContractParamVo> paramVoList = new ArrayList<>();
        if (ObjectUtils.isEmpty(keys)) {
            return paramVoList;
        }
        int i = 0;
        for (String key : keys) {
            ContractParamVo param = new ContractParamVo();
            param.setKey(key);
            param.setPage(Integer.parseInt(pages[i]));
            if (!ObjectUtils.isEmpty(index)) {
                param.setIndex(Integer.parseInt(index[i]));
            }
            paramVoList.add(param);
            i++;
        }
        return paramVoList;
    }

    private OutSideAccountEntity getOutSideAccountEntity(String realName, String idCard, String mobile, String uniqueId) {
        OutSideAccountEntity outSideAccountEntity = new OutSideAccountEntity();
        outSideAccountEntity.setContactsMobile(mobile);
        outSideAccountEntity.setLicenseNumber(idCard);
        outSideAccountEntity.setName(realName);
        outSideAccountEntity.setLoginMobile(mobile);
        outSideAccountEntity.setUniqueId(uniqueId);
        return outSideAccountEntity;
    }
}
